package com.microtf.api.service;

import com.microtf.framework.jpa.StorageRepository;
import com.microtf.framework.jpa.entity.StorageEntity;
import com.microtf.framework.services.miniapp.listener.EventListener;
import com.microtf.framework.services.miniapp.message.input.event.MediaCheckEvent;
import com.microtf.framework.services.miniapp.message.output.OutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class MiniWeChatListen implements EventListener {
    private StorageRepository storageRepository;

    @Autowired
    public void setStorageRepository(StorageRepository storageRepository) {
        this.storageRepository = storageRepository;
    }

    @Override
    public <T extends OutMessage> Optional<T> onEvent(MediaCheckEvent event) {
        StorageEntity storageEntity=new StorageEntity();
        storageEntity.setTraceId(event.getTraceId());
        Optional<StorageEntity> one = storageRepository.findOne(Example.of(storageEntity));
        if(one.isPresent()){
            StorageEntity storageEntity1 = one.get();
            storageEntity1.setCheckResult(event.getResult().getSuggest());
            storageRepository.save(storageEntity1);
        }
        return EventListener.super.onEvent(event);
    }
}
